package 回溯算法;

import java.util.ArrayList;
import java.util.List;

public class combinationSum39 {
    List<List<Integer>> lists;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        lists = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        dfs(candidates, target, lists, list, 0);
        return lists;
    }

    /**
     * @param candidates
     * @param target
     * @param lists
     * @param list
     * @param idx
     */
    public void dfs(int[] candidates, int target, List<List<Integer>> lists, List<Integer> list, int idx) {
        if (idx == candidates.length) {
            return;
        }
        if (target == 0) {
            lists.add(new ArrayList<Integer>(list));
            return;
        }
        // 直接跳过
        dfs(candidates, target, lists, list, idx + 1);
        // 选择当前数
        if (target - candidates[idx] >= 0) {
            list.add(candidates[idx]);
            dfs(candidates, target - candidates[idx], lists, list, idx);
            list.remove(list.size() - 1);
        }
    }
}
